package com.tianquan.mvc;/**
 * @author starsea
 * @date 2024-09-28 下午4:34
 */

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @BelongsProject: uploaddemo
 * @BelongsPackage: com.tianquan.mvc
 * @Author: tianquan
 * @CreateTime: 2024-09-28  16:34
 * @Description: 测试
 * @Version: 1.0
 */
@RestController
public class TransactionManagerTest {

    @Autowired
    private PlatformTransactionManager transactionManager;// 引入 （平台）事务管理器，Spring 事务策略的核心。

    @RequestMapping(method = RequestMethod.GET, value = "/test11")
    public void test() {
        TransactionStatus status = getTransactionDefinition();
        try {
            // 业务代码
            transactionManager.commit(status);// 手动提交事务
        } catch (Exception e) {
            // 异常的时候回滚
            transactionManager.rollback(status);
        }
    }

    public TransactionStatus getTransactionDefinition() {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        // 新发起一个事务
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        return transactionManager.getTransaction(def);
    }


}
